package jp.sinya.register.util;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;

import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

public class CommonUtils {

    /**
     * 1.生成随机的32位长的字符串
     */
    public static String uuid() {
        //这里要用到java.util.UUID包中的randomUUID()方法.
        //String uuid = UUID.randomUUID().toString();

        //生成的格式为：88c7f729-037e-4f4d-a361-71cd91f393a1
        //如果不想要"-",可以使用下面的描述
        String uuid = UUID.randomUUID().toString().replace("-", "");
        return uuid;
    }

    /**
     * 2.将Map中的数据封装到Bean中
     *
     * @param map * @param clazz
     * @return
     */
    public static <T> T toBean(Map map, Class<T> clazz) {
        /**
         * 1.通过clazz创建实例；
         */
        T bean = null;
        try {
            bean = clazz.newInstance();
            ConvertUtils.register(new DateConverter(), Date.class);
            BeanUtils.populate(bean, map);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return bean;

    }

    static class DateConverter implements Converter {
        @Override
        public Object convert(Class aClass, Object value) {
            if (value == null) {
                return null;
            }
            if (!(value instanceof String)) {
                throw new ConversionException("类型不匹配String");
            }
            String str = (String) value;
            if (str.trim().equals("")) {
                return null;
            }

            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

            try {
                return df.parse(str);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }
    }

}